<template>
  <div>
    <div class="mb-8">
      <h2 class="text-2xl font-bold text-gray-900 mb-2">帮助与反馈</h2>
      <p class="text-gray-600">获取帮助和提交反馈，我们会尽快回复您</p>
    </div>

    <div class="mb-8">
      <h3 class="text-lg font-semibold text-gray-900 mb-4">帮助中心</h3>
      <div class="grid grid-cols-3 gap-6">
        <div class="bg-white rounded-lg p-6 hover:shadow-md transition-shadow flex flex-col h-full">
          <div class="w-12 h-12 bg-blue-100 rounded-lg mb-4 flex items-center justify-center">
            <!-- 常见问题：问号图标 -->
            <svg class="w-6 h-6 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
              <path stroke-linecap="round" stroke-linejoin="round" d="M12 18h.01M8.227 8.227A3 3 0 1115 9c0 1.657-1.2 2.4-2.1 3.05-.77.55-1.4 1-1.4 1.95V15" />
              <circle cx="12" cy="12" r="9" stroke-linecap="round" stroke-linejoin="round" />
            </svg>
          </div>
          <h4 class="text-base font-semibold text-gray-900 mb-2">常见问题</h4>
          <p class="text-sm text-gray-600 mb-4">查看最常见的问题和解答</p>
          <button
            type="button"
            class="mt-auto text-sm text-blue-600 font-medium hover:underline text-left"
            @click="$router.push('/courier/profile/help/faq')"
          >
            查看更多 &gt;
          </button>
        </div>
        <div class="bg-white rounded-lg p-6 hover:shadow-md transition-shadow flex flex-col h-full">
          <div class="w-12 h-12 bg-blue-100 rounded-lg mb-4 flex items-center justify-center">
            <!-- 使用指南：书本 / 文档图标 -->
            <svg class="w-6 h-6 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
              <path stroke-linecap="round" stroke-linejoin="round" d="M4 5a2 2 0 012-2h8.5A1.5 1.5 0 0116 4.5V19a1 1 0 01-1.447.894L11 18.118l-3.553 1.776A1 1 0 016 19V5z" />
              <path stroke-linecap="round" stroke-linejoin="round" d="M9 8h4m-4 3h2" />
            </svg>
          </div>
          <h4 class="text-base font-semibold text-gray-900 mb-2">使用指南</h4>
          <p class="text-sm text-gray-600 mb-4">了解如何使用平台</p>
          <button
            type="button"
            class="mt-auto text-sm text-blue-600 font-medium hover:underline text-left"
            @click="$router.push('/courier/profile/help/guide')"
          >
            查看更多 &gt;
          </button>
        </div>
        <div class="bg-white rounded-lg p-6 hover:shadow-md transition-shadow cursor-pointer flex flex-col h-full" @click="contactAdmin">
          <div class="w-12 h-12 bg-blue-100 rounded-lg mb-4 flex items-center justify-center">
            <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
            </svg>
          </div>
          <h4 class="text-base font-semibold text-gray-900 mb-2">联系管理员</h4>
          <p class="text-sm text-gray-600 mb-4">遇到问题？联系我们</p>
          <span class="mt-auto text-sm text-blue-600 font-medium">立即联系 &gt;</span>
        </div>
      </div>
    </div>

    <div class="bg-white rounded-lg p-6">
      <h3 class="text-lg font-semibold text-gray-900 mb-2">意见反馈</h3>
      <p class="text-sm text-gray-600 mb-6">有任何问题或建议，请告诉我们</p>
      <form @submit.prevent="submitFeedback">
        <div class="mb-6"><label class="block text-sm font-medium text-gray-700 mb-3">反馈内容</label><textarea v-model="feedbackForm.content" rows="6" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none text-sm" placeholder="请详细描述..." required></textarea></div>
        <div class="mb-6"><label class="block text-sm font-medium text-gray-700 mb-3">联系方式（选填）</label><input v-model="feedbackForm.contact" type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" placeholder="请留下您的手机号或邮箱"/></div>
        <div class="flex justify-end"><button type="submit" :disabled="isSubmitting" class="px-6 py-3 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed">{{ isSubmitting ? '提交中...' : '提交反馈' }}</button></div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'CourierHelp',
  data() {
    return {
      feedbackForm: {
        content: '',
        contact: ''
      },
      isSubmitting: false
    }
  },
  methods: {
    async contactAdmin() {
      const userId = Number(localStorage.getItem('userId'))
      if (!userId) {
        ElMessage.warning('请先登录')
        this.$router.push('/login')
        return
      }
      try {
        // 获取管理员列表
        const { data: adminData } = await axios.get('/api/users/admins')
        const admins = (adminData && adminData.data) || []
        if (admins.length === 0) {
          ElMessage.info('暂无在线管理员，请稍后再试')
          return
        }
        // 选择第一个管理员建立会话
        const adminId = admins[0].id
        const { data: convData } = await axios.post('/api/messages/conversations', {
          participants: [userId, adminId],
          type: 1 // 私聊
        })
        const cid = convData && convData.data && convData.data.id
        if (cid) {
          this.$router.push({ path: '/messages', query: { cid } })
        } else {
          ElMessage.error('无法创建会话，请稍后再试')
        }
      } catch (e) {
        console.error('联系管理员失败', e)
        ElMessage.error('联系管理员失败，请稍后再试')
      }
    },
    async submitFeedback() {
      if (!this.feedbackForm.content.trim()) {
        ElMessage.warning('请输入反馈内容')
        return
      }

      const userId = localStorage.getItem('userId')
      if (!userId) {
        ElMessage.warning('请先登录')
        this.$router.push('/login')
        return
      }

      this.isSubmitting = true

      try {
        const response = await fetch('/api/feedback', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userId: userId,
            userType: 'courier',
            content: this.feedbackForm.content,
            contact: this.feedbackForm.contact || null
          })
        })

        const result = await response.json()

        if (result.success) {
          ElMessage.success('反馈提交成功，我们会尽快处理')
          this.feedbackForm = {
            content: '',
            contact: ''
          }
        } else {
          ElMessage.error(result.message || '提交失败')
        }
      } catch (error) {
        console.error('提交反馈失败:', error)
        ElMessage.error('网络错误，请稍后再试')
      } finally {
        this.isSubmitting = false
      }
    }
  }
}
</script>
